package cn.dm.service;

import cn.dm.common.DateUtil;
import cn.dm.common.MD5;
import cn.dm.common.RedisUtils;
import cn.dm.common.UserAgentUtil;
import cn.dm.pojo.DmUser;
import cz.mallat.uasparser.UserAgentInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {
    private String tokenPrefix = "token:";//统一加入 token前缀标识

    /**
     * 生成Token
     *
     * @param agent Http头中的user-agent信息
     * @param user  用户信息
     * @return PC：“前缀PC-USERCODE-USERID-CREATIONDATE-RANDEM[6位]”
     * MOBILE：“前缀MOBILE-USERCODE-USERID-CREATIONDATE-RANDEM[6位]”
     */
    @Override
    public String generateToken(String agent, DmUser user) throws Exception {
        StringBuffer tokenStr = new StringBuffer();
        //前缀
        tokenStr.append(tokenPrefix);
        UserAgentInfo userAgentInfo = UserAgentUtil.getUasParser().parse(agent);
        if (userAgentInfo.getDeviceType().equals(UserAgentInfo.UNKNOWN)) {
            if (UserAgentUtil.CheckAgent(agent)) {
                tokenStr.append("MOBILE-");
            } else {
                tokenStr.append("PC-");
            }
        } else if (userAgentInfo.getDeviceType().equals("Personal computer")) {
            tokenStr.append("PC-");
        } else {
            tokenStr.append("MOBILE-");
        }
        tokenStr.append(MD5.getMd5(user.getPhone(), 32));
        tokenStr.append("-");
        tokenStr.append(user.getId());
        tokenStr.append("-");
        tokenStr.append(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        tokenStr.append("-");
        tokenStr.append(MD5.getMd5(agent, 6));
        return tokenStr.toString();
    }

    /**
     * 删除token
     *
     * @param token
     * @throws Exception
     */

    @Resource
    private RedisUtils redisAPI;

    @Override
    public void deleteToken(String token) throws Exception {
        redisAPI.delete(token);
    }
}
